<template>
  <el-dialog
    :title="isEdit?$t('message.edit') + $t('message.cjhd'):$t('message.add') + $t('message.cjhd')"
    :visible.sync="isShow"
    :close-on-click-modal="modalDialog"
    :close-on-press-escape="modalDialog"
    @close="addClose"
  >
    <el-form
      ref="luckydrawForm"
      :model="luckydrawForm"
      label-suffix="："
      label-width="auto"
      :rules="rules"
    >
      <el-form-item :label="$t('message.hdname')" prop="name">
        <el-input v-model="luckydrawForm.name" :placeholder="$t('message.qsr')" />
      </el-form-item>
      <el-form-item :label="$t('message.hdimg')" prop="showPic">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="PUBLIC_IMG"
            :fixed-number="[32, 32]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <el-upload
          class="device-uploader"
          :action="uploadFileUrl"
          :data="uploadData"
          :show-file-list="false"
          accept=".jpg,.png"
          :on-change="addFileChange"
          :auto-upload="false"
        >
          <i v-show="!luckydrawForm.showPic" class="el-icon-plus uploader-icon" />
          <div
            v-show="luckydrawForm.showPic"
            class="file"
            :style="'background-image: url(' + luckydrawForm.showPic + ')'"
          >
            <div class="delete">
              <i
                class="el-icon-delete icon"
                @click.stop="deleteDeviceConfigAddImage"
              />
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item :label="$t('message.ksrq')" prop="beginDate">
        <el-date-picker
          v-model="luckydrawForm.beginDate"
          type="date"
          value-format="yyyy-MM-dd"
          :placeholder="$t('message.qxz')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="$t('message.jsrq')" prop="endDate">
        <el-date-picker
          v-model="luckydrawForm.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          :placeholder="$t('message.qxz')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="$t('message.kssj')" prop="beginTime">
        <el-time-select
          v-model="luckydrawForm.beginTime"
          style="width: 100%"
          :picker-options="{
            start: '00:00',
            step: '01:00',
            end: '23:00'
          }"
          :placeholder="$t('message.qxz')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.jssj')" prop="endTime">
        <el-time-select
          v-model="luckydrawForm.endTime"
          style="width: 100%"
          :picker-options="{
            start: '00:00',
            step: '01:00',
            end: '23:00'
          }"
          :placeholder="$t('message.qxz')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.drdrxc')" prop="dayLimit">
        <el-input v-model="luckydrawForm.dayLimit" :placeholder="$t('message.drdrxc') + '(' + $t('message.dbbxz') + ')'" />
      </el-form-item>
      <el-form-item :label="$t('message.drzxc')" prop="singleLimit">
        <el-input v-model="luckydrawForm.singleLimit" :placeholder="$t('message.drzxc') + '(' + $t('message.dbbxz') + ')'" />
      </el-form-item>
      <el-form-item :label="$t('message.hdms')" prop="description">
        <el-input v-model="luckydrawForm.description" type="textarea" :placeholder="$t('message.qsr')" />
      </el-form-item>

    </el-form>
    <div slot="footer" class="custome-footer">
      <div>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="confirmAction">{{ $t('message.qr') }}</el-button>
        <el-button @click="isShow=false">{{ $t('message.qx') }}</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { uploadFile, addLuckdrawAcyivity, getLuckdrawAcyivityDetial, updateLuckdrawAcyivity } from '@/api'
import Cropper from '@/components/cropper'
import store from '@/store'
export default {
  components: {
    Cropper
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      subLoading: false,
      isShow: false,
      isEdit: false,
      dialogCropperVisible: false,
      uploadFileUrl: uploadFile,
      uploadData: {
        folder: 'PUBLIC_IMG',
        type: ''
      },
      luckydrawForm: {
        name: '',
        showPic: '',
        beginDate: '',
        endDate: '',
        beginTime: '',
        endTime: '',
        description: ''
      },
      optionImg: '',
      param: {},
      files: {},
      fileinfo: {},
      rules: {
        name: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.hdname'), trigger: 'blur' }
        ],
        showPic: [
          { required: true, message: this.$t('message.qsc') + this.$t('message.hdimg'), trigger: 'blur' }
        ],
        beginDate: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.ksrq'), trigger: 'change' }
        ],
        endDate: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.jsrq'), trigger: 'change' }
        ],
        beginTime: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.kssj'), trigger: 'change' }
        ],
        endTime: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.jssj'), trigger: 'change' }
        ],
        description: [
          { required: true, message: this.$t('message.qsr') + this.$t('message.hdms'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     * @关闭弹框回调
     */
    addClose() {
      // this.luckydrawForm = {}
      this.$refs.luckydrawForm.resetFields()
    },
    /**
     * @弹框
     */
    open(id) {
      this.isShow = true
      this.isEdit = false
      if (id !== undefined) {
        this.isEdit = true
        getLuckdrawAcyivityDetial({ param: { id }})
          .then(res => {
            console.log(res)
            this.luckydrawForm = res.record
            this.$set(this.luckydrawForm, 'endTime', res.record.endTime)
            this.$set(this.luckydrawForm, 'beginTime', res.record.beginTime)
          })
      }
    },
    /**
     * @desc 上传图片成功回调
     * @param {*} response
     * @param {*} file
     * @param {文件} fileList
     */
    uploadSuccess(response, file, fileList) {
      // console.log(response);
      this.luckydrawForm.pic = response.insertUrl
      this.$set(this.luckydrawForm, 'showPic', response.showUrl)
      this.$refs.luckydrawForm.clearValidate()
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.luckydrawForm, 'showPic', config.showUrl)
        this.luckydrawForm.pic = config.insertUrl
        this.fileinfo = config
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        // this.$refs.ruleForm.clearValidate();
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    deleteDeviceConfigAddImage() {
      this.luckydrawForm.pic = ''
      this.$set(this.luckydrawForm, 'showPic', '')
    },
    /**
     * @确认
     */
    confirmAction() {
      // console.log(this.luckydrawForm);
      this.$refs.luckydrawForm.validate(v => {
        if (v) {
          const form = { ...this.luckydrawForm }
          form.beginTime = this.luckydrawForm.beginTime.split(':')[0]
          form.endTime = this.luckydrawForm.endTime.split(':')[0]
          // console.log(this.luckydrawForm);
          const action = this.isEdit ? updateLuckdrawAcyivity : addLuckdrawAcyivity
          this.subLoading = true
          action(form)
            .then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.isShow = false
                this.$emit('success')
              } else {
                this.$message.error(res.errorMsg)
              }
            }).catch(() => {
              this.subLoading = false
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

@import "@/styles/variables.scss";
.input-style {
  display: flex;
}
.device-uploader {
  position: relative;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.custome-footer {
  display: flex;
  flex-direction: row-reverse;
}
</style>
